package com.leetcode.No2363;

import org.junit.Test;

import java.util.*;

/**
 * 合并相似的物品
 */
public class Solution {

    public List<List<Integer>> mergeSimilarItems(int[][] items1, int[][] items2) {
        TreeMap<Integer, Integer> treeMap = new TreeMap<>();
        for (int[] item : items1) {
            Integer weight = treeMap.get(item[0]);
            if (weight == null) {
                weight = item[1];
            } else {
                weight += item[1];
            }
            treeMap.put(item[0], weight);
        }
        for (int[] item : items2) {
            Integer weight = treeMap.get(item[0]);
            if (weight == null) {
                weight = item[1];
            } else {
                weight += item[1];
            }
            treeMap.put(item[0], weight);
        }
        int size = treeMap.size();
        List<List<Integer>> result = new ArrayList<>(size);
        while (treeMap.size() > 0) {
            Map.Entry<Integer, Integer> entry = treeMap.pollFirstEntry();
            ArrayList<Integer> item = new ArrayList<>(2);
            item.add(entry.getKey());
            item.add(entry.getValue());
            result.add(item);
        }
        return result;
    }

    @Test
    public void test01() {
        int[][] items1;
        int[][] items2;

        // items1 = [[1,1],[4,5],[3,8]], items2 = [[3,1],[1,5]]
        // [[1,6],[3,9],[4,5]]
        items1 = new int[][]{{1,1},{4,5},{3,8}};
        items2 = new int[][]{{3,1},{1,5}};
        System.out.println(mergeSimilarItems(items1, items2));

        // items1 = [[1,1],[3,2],[2,3]], items2 = [[2,1],[3,2],[1,3]]
        // [[1,4],[2,4],[3,4]]
        items1 = new int[][]{{1,1},{3,2},{2,3}};
        items2 = new int[][]{{2,1},{3,2},{1,3}};
        System.out.println(mergeSimilarItems(items1, items2));

        // items1 = [[1,3],[2,2]], items2 = [[7,1],[2,2],[1,4]]
        // [[1,7],[2,4],[7,1]]
        items1 = new int[][]{{1,3},{2,2}};
        items2 = new int[][]{{7,1},{2,2},{1,4}};
        System.out.println(mergeSimilarItems(items1, items2));
    }

}
